# -*- coding:utf-8 -*-

import json

from tornado import web, gen
import tornado_mysql
from tornado.ioloop import IOLoop

from util import PoolManager, get_logger, parse_result, parse_json
from entity import User,ERROR_CODE

log = get_logger(__name__)


class LoginHandle(web.RequestHandler):
    @gen.coroutine
    def post(self):
        username = self.get_body_argument('username')
        passwd = self.get_body_argument('passwd')
        cur = yield self.query_user(username, passwd)
        user_info = cur.fetchone()
        if user_info:
            log.info(user_info)
            user = User()
            user.setter(id=user_info[0], username=user_info[1], passwd=user_info[2])
            self.set_cookie("token", "123456")
            self.write(parse_json(parse_result(0, user)))
        else:
            log.info("输入密码有误: {0} {1}".format(username, passwd))
            self.write(parse_json(parse_result(ERROR_CODE.ERROR_PASSWD)))

    @gen.coroutine
    def query_user(self, username, passwd):
        sql = "SELECT user.id,user.account,user.passwd FROM user WHERE account=\'{0}\' AND passwd=\'{1}\'".format(
            username, passwd)
        log.info(sql)
        cur = yield PoolManager().instance().pool.execute(sql)
        raise gen.Return(cur)


class RegisterHandler(web.RequestHandler):
    @gen.coroutine
    def post(self):
        username = self.get_body_argument('username')
        passwd = self.get_body_argument('passwd')
        res = yield self.create_user(username, passwd)
        if res:
            self.write(parse_json(parse_result(0)))
        else:
            log.info("注册失败: {0} {1}".format(username, passwd))
            self.write(parse_json(parse_result(ERROR_CODE.DUPLICATE_USER)))

    @gen.coroutine
    def create_user(self, username, passwd):
        sql = "INSERT INTO user (account,passwd) VALUES(\'{0}\',\'{1}\')".format(
            username, passwd)
        log.info(sql)
        try:
            yield PoolManager().instance().pool.execute(sql)
        except Exception as e:
            log.info(e)
            raise gen.Return(False)
        raise gen.Return(True)

